#!/usr/bin/env python
#-*- coding:utf-8 -*-

"""

"""

from __future__ import division

from tools import *
from visualise import *
from drawing import *

class Feature(object):
	def __init__(self, pos, descriptor=None, bbox=None):
		self.pos = pos
		self.descriptor = descriptor
		self.bbox = bbox

	def draw(self, image):
		draw_cross(image, [self.pos])
		if self.bbox:
			self.bbox.draw(image)

class SurfFeature(Feature):
	pass

class MserFeature(Feature):
	pass

def get_surf_features(image, mask=None):
	start_time = time.time()

	png_filename = temp_filename(".png")
	pgm_filename = temp_filename(".pgm")
	txt_filename = temp_filename(".txt")

	save_image(png_filename, image)
	result = execute(["convert", png_filename, pgm_filename])
	assert not result.split(), result

	result = execute(["surf.ln", "-q", "-e", "-i", pgm_filename, "-o", txt_filename, "-thres", "500"])
	assert not result, result

	# read keypoints file
	f = file(txt_filename)
	feature_len = int(f.readline().strip()) - 1
	nr_features = int(f.readline().strip())

	features = []
	for line in f:
		data = map(float, line.strip().split(" "))
		u, v, a, b, c = data[:5]
		orientation = data[5]
		descriptor = asarray(data[6:])
		assert len(descriptor) == feature_len, len(descriptor)

		feature = SurfFeature(pos=(int(v),int(u)), descriptor=descriptor, bbox=None)
		features.append(feature)

	assert len(features) == nr_features

	logger.debug("extracted %d surf in %0.2fs" % (len(features), time.time() - start_time))

	return [f for f in features if mask is None or mask[f.pos]]

def get_fast_corners(image, threshold=100):
	"""
	http://mi.eng.cam.ac.uk/~er258/work/fast.html
	"""
	start_time = time.time()
	image_filename = temp_filename(".bmp")

	save_image(image_filename, image)

	#~ start_time = time.time()
	result = execute(["fast-Linux-i686", "-l", "-s", "-t", threshold, "-n", 9, image_filename])
	#~ print time.time() - start_time, "sec"

	if not result.strip():
		return []

	assert "Error" not in result, result

	features = []
	for line in result.split("\n"):
		y, x = line.split(" ")
		feature = Feature(pos=(int(x), int(y)))
		features.append(feature)

	logger.debug("extracted %d corners in %0.2fs" % (len(features), time.time() - start_time))

	return features

def get_mser_features(image, mask=None):
	"""
	http://www.vlfeat.org/
	"""
	start_time = time.time()

	png_filename = temp_filename(".png")
	pgm_filename = os.path.join(FAST_TEMP_DIRECTORY, "mser_extraction.pgm")

	save_image(png_filename, image)
	result = execute(["convert", png_filename, pgm_filename])
	assert not result.split(), result

	result = execute(["mser", pgm_filename], cwd=FAST_TEMP_DIRECTORY)
	assert not result, result

	# read keypoints file
	txt_filename = os.path.join(FAST_TEMP_DIRECTORY, "mser_extraction.frame")
	features = []
	for line in file(txt_filename):
		x, y, a, b, c = map(float, line.strip().split(" "))
		feature = MserFeature(pos=(int(y), int(x)), descriptor=(a,b,c), bbox=None)
		features.append(feature)
	os.remove(txt_filename)

	logger.debug("extracted %d mser in %0.2fs" % (len(features), time.time() - start_time))

	return [f for f in features if mask is None or mask[f.pos]]

def main():
	v = Viewer()
	image = load_image("../media/broccoli.jpg")
	image = imresize(image, 0.5)
	print image.shape
	#~ features = get_surf_features(image)
	#~ features = get_fast_corners(image, threshold=150)
	features = get_mser_features(image)
	print len(features)
	for feature in features:
		feature.draw(image)
	v.update_image(image)
	while Viewer.instances:
		Viewer.draw_all()

if __name__ == '__main__':
	main()
